package db_sports

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

// GetFootballInitialOdds 足球的初始指数
func GetFootballInitialOdds(matchId int, exType string) ([]models_sports.FootballOdds, error) {
	// NOTICE : 这里因为sharding 驱动不支持的原因，现在只能手动计算分片
	tableFormat := fmt.Sprintf("_%03d", matchId%128)
	sql := `
	SELECT * FROM (
			SELECT
				bo.*
			FROM
				( SELECT * FROM db_football_odds%s WHERE  match_id = ? AND exponential_type = ? ORDER BY change_time ASC LIMIT 10000 ) AS bo 
			GROUP BY
				exponential_type,
				company_id
				LIMIT 1000
	) as cc ORDER BY cc.change_time ASC 
	`
	records := make([]models_sports.FootballOdds, 0)

	err := global2.Sport().Raw(fmt.Sprintf(sql, tableFormat), matchId, exType).Scan(&records).Error
	if err != nil {
		return records, err
	}
	return records, nil
}

// GetFootballRealTimeOdds 足球的实时数据
func GetFootballRealTimeOdds(matchId int, exType string) ([]models_sports.FootballOdds, error) {
	// NOTICE : 这里因为sharding 驱动不支持的原因，现在只能手动计算分片
	tableFormat := fmt.Sprintf("_%03d", matchId%128)
	sql := `
	SELECT * FROM (
			SELECT
				bo.*
			FROM
				( SELECT * FROM db_football_odds%s WHERE  match_id = ? AND exponential_type = ? ORDER BY change_time DESC LIMIT 10000 ) AS bo 
			GROUP BY
				exponential_type,
				company_id
				LIMIT 1000
	) as cc ORDER BY cc.change_time DESC 
	`
	records := make([]models_sports.FootballOdds, 0)

	err := global2.Sport().Raw(fmt.Sprintf(sql, tableFormat), matchId, exType).Scan(&records).Error
	if err != nil {
		return records, err
	}
	return records, nil
}

// GetFootballHistoryOdds 足球历史指数
func GetFootballHistoryOdds(matchId, companyId int, exType string) ([]models_sports.FootballOdds, error) {
	records := make([]models_sports.FootballOdds, 0)
	model := global2.SportSharding().Model(&models_sports.FootballOdds{})
	if companyId > 0 {
		model.Where("company_id = ?", companyId)
	}
	model.Where("match_id = ?", matchId).
		Where("exponential_type = ?", exType)
	err := model.Order("change_time asc").
		Find(&records).Error
	if err != nil {
		global2.Log.Error("err: ", err)
		return records, err
	}
	return records, nil
}
